#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
script name: api
Created on 2020/3/10 13:43 by PyCharm
@author: fujianjian
"""
from flask import jsonify, request

from app import db, DEFAULT_PAGE_NO, DEFAULT_PAGE_SIZE
from . import plan_blueprint

from ..model.plan import Plan, PlanItem


@plan_blueprint.route('/data', methods=['post', 'get'])
def data():
    paramJson = request.get_json()
    print('fetch plan data:', paramJson)
    condition = set()
    if 'name' in paramJson:
        condition.add(Plan.name == paramJson.get('name'))

    plan_page = Plan.query.filter(*condition).paginate(int(paramJson.get('pageno', DEFAULT_PAGE_NO)),
                                                       int(paramJson.get('pagesize', DEFAULT_PAGE_SIZE)))

    data = {'total': plan_page.total, 'content': plan_page.items}
    ret = {'code': 200, 'msg': 'success', 'data': data}
    return jsonify(ret)


@plan_blueprint.route('/modify', methods=['post', 'get'])
def add_plan():
    plan_json = request.get_json()
    print('add plan json', plan_json)

    plan = Plan.query.filter(Plan.id == plan_json.get('id', '')).first()
    if plan:
        plan.name=plan_json.get('name')
    else:
        plan = Plan(id=plan_json.get('id'), name=plan_json.get('name'))
    db.session.add(plan)
    db.session.flush()

    if plan_json.get('items'):
        # 按条件批量删除数据库中的数据
        # db.session.query(PlanItem).filter(PlanItem.plan_id == plan.id).delete()
        PlanItem.query.filter(PlanItem.plan_id == plan.id).delete()
    item_list = [PlanItem(id=item.get('id'), plan_id=plan.id, timeline=item.get('timeline'), seq=item.get('seq'),
                          plan_desc=item.get('plan_desc')) for item in plan_json.get('items', [])]
    db.session.add_all(item_list)
    db.session.commit()

    ret = {'code': 200, 'msg': 'success'}
    return jsonify(ret)
